//
//  SubcribeSectionController.m
//  NewsReader
//
//  Created by blacksun on 10-12-7.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "SubcribeSectionController.h"
#import "RootViewController.h"


@implementation SubcribeSectionController
@synthesize sections,httpUtils,inprocessDownload,tableView,titelLabel,loadingView;
@synthesize subcribedSectionIds;


#pragma mark -
#pragma mark Initialization

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	self.httpUtils = [NSMutableArray array];
	NSMutableArray *array = [[NSMutableArray alloc] init];
	self.subcribedSectionIds = array;
	[array release];
	self.inprocessDownload = [NSMutableDictionary dictionary];
	self.titelLabel.text = self.title;
	if (!self.sections) {
		NSURL *url = [[NSURL alloc] initWithString:[URLAddress listAllSections]];
		NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
		HttpUtil *httpUtil = [[HttpUtil alloc] init];
		[self.httpUtils addObject:httpUtil];
		[httpUtil performRequest:request withTarget:self andCallBackAction:@selector(finishHttpRequest:) isBackGround:YES];
		[httpUtil release];
		[request release];
		[url release];
		self.loadingView.hidden = NO;
	}else {
		/*不再做已订阅section的过滤，而是选中已订阅的section，但是不能取消选择
		NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
		NSMutableArray *array = [[NSMutableArray alloc] init];
		for (Section *mySection in delegate.user.mySections) {
			for (Section *newSection in self.sections) {
				if ([newSection.sectionId isEqualToString:mySection.sectionId]) {
					[array addObject:newSection];
				}
			}
		}
		[self.sections removeObjectsInArray:array];
		[array release];*/
		
		NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
		
		//NSLog(@"user section size = %d",[delegate.user.mySections count]);
		for (Section *mySection in delegate.user.mySections) {
			[self.subcribedSectionIds addObject:mySection.sectionId];
		}
		
	}

}

-(IBAction)goBack:(id)sender{
	[self.navigationController popViewControllerAnimated:YES];
}

-(void) finishHttpRequest:(NSMutableData *)responseData{
	NSArray *sectionsArray  = nil;
	NSString *responseStr= nil;
	if (responseData) {
		responseStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
		NSDictionary * responseDict = [responseStr JSONValue];
		sectionsArray= [responseDict objectForKey:@"sections"];
	}else {
		sectionsArray = [NSMutableArray array];
	}

	NSMutableArray *inServerSections = inServerSections =  [ModelParseUtil parseSectionsFromJsonArray:sectionsArray];
	[responseStr release];	
	[responseData release];
	[self performSelectorOnMainThread:@selector(reloadTableView:) withObject:inServerSections waitUntilDone:NO];
	
}
-(void)reloadTableView:(NSMutableArray *)newSetions{
	self.sections = newSetions;
	[self.tableView reloadData];
	self.loadingView.hidden = YES;
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	//self.navigationController.navigationBarHidden = NO;
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
	[self.httpUtils makeObjectsPerformSelector:@selector(stopHttpConnection)];
	[[self.inprocessDownload allValues] makeObjectsPerformSelector:@selector(cancelDownload)];
}

/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [self.sections count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"SubcribeCell";
    
    UITableViewCell *cell = [atableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
	
	NSInteger row = [indexPath row];
	Section *currentSection = [self.sections objectAtIndex:row];
	
	if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		UIImageView *backImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"list_bg_new.png"]];
		cell.backgroundView = backImageView;
		[backImageView release];
		
		CGRect labelRect =  CGRectMake(65.0, 17.0, 200.0, 30.0);
		
		if (!currentSection.leaf) {
			UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5.0, 5.0, 54.0, 54.0)];
			imageView.tag = kImageViewTag;
			[cell.contentView addSubview:imageView];
			[imageView release];
		}else {
			labelRect = CGRectMake(15.0, 17.0, 200.0, 30.0);
		}
		UILabel *label = [[UILabel alloc] initWithFrame:labelRect];
		label.backgroundColor = [UIColor clearColor];
		label.font = [UIFont boldSystemFontOfSize:18.0];
		label.tag = kLabelTag;
		[cell.contentView addSubview:label];
		[label release];

		UIImageView *subcribeImage = [[UIImageView alloc] initWithFrame:CGRectMake(250.0, 10.0, 30.0, 30.0)];
		subcribeImage.tag = kSubcribeIamgeTag;
		[cell.contentView addSubview:subcribeImage];
		[subcribeImage release];
    }
	
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	
	UIImageView *subcribeImage = (UIImageView *)[cell.contentView viewWithTag:kSubcribeIamgeTag];
	if ([delegate.rootViewController.needAddSections containsObject:currentSection]) {
		subcribeImage.image = [UIImage imageNamed:@"subcribe.png"];
	}else if (currentSection.leaf == NO) {//如果是父节点
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	}else if ([self.subcribedSectionIds containsObject:currentSection.sectionId	]) {
		subcribeImage.image = [UIImage imageNamed:@"subcribed.png"];
		
		UIImageView *backImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sb_bg.png"]];
		cell.backgroundView = backImageView;
		[backImageView release];
	}else {
		//
	}

	
	UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:kImageViewTag];
	if (!imageView) {
		//如果没有图片
	}
	if (currentSection.icon) {
		imageView.image = currentSection.icon;
	}else {
		UIImage *loading =  [UIImage imageNamed:@"loading3.png"];
		imageView.image = loading;
		
		
		ImageDownloader *downloader = [[ImageDownloader alloc] init];
		downloader.delegate = self;
		downloader.imageUrl = currentSection.imageUrl;
		downloader.identifier = indexPath;
		[downloader startDownload];
		[self.inprocessDownload setObject:downloader forKey:indexPath];
		[downloader release];
	}
	
	UILabel *textLable = (UILabel *)[cell.contentView viewWithTag:kLabelTag];

    textLable.text = currentSection.sectionName;
    
    return cell;
}

- (void)imageLoaded:(UIImage *)image forIdentify:(NSObject *)identifier{
	NSIndexPath *indexPath = (NSIndexPath *)identifier;
	UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
	Section *currentSection = [self.sections objectAtIndex:[indexPath row]];
	UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:kImageViewTag];
	imageView.image = image;
	currentSection.icon = image;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	return 64.0;
}

- (void)tableView:(UITableView *)atableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSInteger row = [indexPath row];
	Section *currentSection = [self.sections objectAtIndex:row];
	if (currentSection.leaf == NO) {
		SubcribeSectionController *controller = [[SubcribeSectionController alloc] initWithNibName:@"SubcribeSectionController" bundle:nil];
		controller.sections = currentSection.childSections;
		controller.title = currentSection.sectionName;
		[self.navigationController pushViewController:controller animated:YES];
		[controller release];
	}else {
		NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
		UITableViewCell *cell = [atableView cellForRowAtIndexPath:indexPath];
		UIImageView *subcribeImage = (UIImageView *)[cell.contentView viewWithTag:kSubcribeIamgeTag];
		if ([self.subcribedSectionIds containsObject:currentSection.sectionId]) {
			//do nothing,如果是已订阅的section，不做任何操作
		}
		else if (subcribeImage.image) {
			subcribeImage.image = nil;
			[delegate.rootViewController.needAddSections removeObject:currentSection];
		}else {
			subcribeImage.image = [UIImage imageNamed:@"subcribe.png"];
			[delegate.rootViewController.needAddSections addObject:currentSection];
		}

	}

}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[[self.inprocessDownload allValues] makeObjectsPerformSelector:@selector(cancelDownload)];
	[self.inprocessDownload release];
	[self.loadingView release];
	[self.titelLabel release];
	[self.tableView release];
	[self.httpUtils release];
	[self.sections release];
	self.subcribedSectionIds = nil;
    [super dealloc];
}


@end

